package com.yuan.java.reg;

import org.junit.Test;

import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * @author yuaneg 2019/1/4
 */
public class PathMatchUtil {

    private static final String PATTERN_LINE_START = "^";

    private static final String PATTERN_LINE_END = "$";

    private static final char[] META_CHARACTERS = {'$', '^', '[', ']', '(', ')',
            '{', '}', '|', '+', '.', '\\'};


    public static boolean wildcardMatch(String pattern, String str) {
        pattern = convertToRegexPattern(pattern);
        return Pattern.matches(pattern, str);
    }

    private static String convertToRegexPattern(String wildcardString) {
        StringBuilder result = new StringBuilder(PATTERN_LINE_START);
        char[] chars = wildcardString.toCharArray();
        for (char ch : chars) {
            if (Arrays.binarySearch(META_CHARACTERS, ch) >= 0) {
                result.append("\\").append(ch);
                continue;
            }
            switch (ch) {
                case '*':
                    result.append(".*");
                    break;
                case '?':
                    result.append(".{0,1}");
                    break;
                default:
                    result.append(ch);
            }
        }
        result.append(PATTERN_LINE_END);
        return result.toString();
    }

    @Test
    public void ttt() {
        test("*", "toto");
        test("toto.java", "tutu.java");
        test("12345", "1234");
        test("1234", "12345");
        test("*f", "");
        test("***", "toto");
        test("*.java", "toto.");
        test("*.java", "toto.jav");
        test("*.java", "toto.java");
        test("abc*", "");
        test("a*c", "abbbbbccccc");
        test("abc*xyz", "abcxxxyz");
        test("*xyz", "abcxxxyz");
        test("abc**xyz", "abcxxxyz");
        test("abc**x", "abcxxx");
        test("*a*b*c**x", "aaabcxxx");
        test("abc*x*yz", "abcxxxyz");
        test("abc*x*yz*", "abcxxxyz");
        test("a*b*c*x*yf*z*", "aabbccxxxeeyffz");
        test("a*b*c*x*yf*zze", "aabbccxxxeeyffz");
        test("a*b*c*x*yf*ze", "aabbccxxxeeyffz");
        test("a*b*c*x*yf*ze", "aabbccxxxeeyfze");
        test("*LogServerInterface*.java", "_LogServerInterfaceImpl.java");
        test("abc*xyz", "abcxyxyz");
    }

    private static void test(String pattern, String str) {
        System.out.println(pattern + "||" + str + "=>>" + wildcardMatch(pattern, str));
    }
}